const express = require("express");
const path = require("path");
const jwt = require("jsonwebtoken");

const SECRET = "secret";
const MY_ACCESS_TOKEN = "my_access_token";
const MY_REFRESH_TOKEN = "my_refresh_token";
var router = express.Router();
const refreshTokenMap = new Map();
const { ListModel } = require("../model/model");
const UniSMS = require("unisms").default;
const app=express
// import UniSMS from "unisms";

router.get("/", (req, res) => {
  const accessToken = req.cookies[MY_ACCESS_TOKEN];
  if (!accessToken) {
    return res.status(401).send("Unauthorized");
  }
});

router.get("/yzm", async (req, res) => {
  let { tel } = req.query;
  const client = new UniSMS({
    accessKeyId: "SH5yka9qXV3xpvThX55ttmJzJKn1icbjgnMZGC4emof9YUW3r",
  });
  let len = Math.floor(1000 + Math.random() * 9000);
  res.status(200).send({ len: len });
  // client
  //   .send({
  //     to: tel,
  //     signature: "刘子硕",
  //     templateId: "pub_verif_login",
  //     templateData: {
  //       code: len,
  //     },
  //   })
  //   .then((ret) => {
  //     res.send({ code: ret.code, len: len, token: token });
  //   })
  //   .catch((e) => {
  //     console.error(e);
  // });
});
  router.post("/addlist", async (req, res) => {
    let { tel } = req.body;

    let ss = await ListModel.find({ tel: tel });

    if (ss.length == 0) {
      await ListModel.create({
        tel: tel,
        password: "admin",
        img: "",
        desc: "",
        name: "",
      });
      res.send("添加成功");
    }
    if (ss.length !== 0) {
      const accessToken = jwt.sign({ tel }, SECRET, { expiresIn: "2s" });
      const refreshToken = jwt.sign({ tel }, SECRET, { expiresIn: "1d" });
      const refreshTokens = refreshTokenMap.get(tel) || [];
      refreshTokens.push(refreshToken);
      refreshTokenMap.set(tel, refreshTokens);
      res.cookie(MY_ACCESS_TOKEN, accessToken, {
        httpOnly: false,
        secure: true,
        sameSite: "strict",
        maxAge: 2 * 1000,
      });
      res.cookie(MY_REFRESH_TOKEN, refreshToken, {
        httpOnly: false,
        secure: true,
        sameSite: "strict",
        maxAge: 1 * 1000 * 60 * 60 * 12,
      });
      return res.status(200).send({ ss });
    }
    return res.send("username or password is incorrect");
  });

  router.post("/login", async (req, res) => {
    const { tel, password } = req.body;
    let ss = await ListModel.find({
      $and: [{ tel: tel }, { password: password }],
    });

    let bb = await ListModel.find({ tel: tel });
    if (ss.length !== 0 || bb.length !== 0) {
      const accessToken = jwt.sign({ tel }, SECRET, { expiresIn: "2s" });
      const refreshToken = jwt.sign({ tel }, SECRET, { expiresIn: "1d" });
      const refreshTokens = refreshTokenMap.get(tel) || [];
      refreshTokens.push(refreshToken);
      refreshTokenMap.set(tel, refreshTokens);
      res.cookie(MY_ACCESS_TOKEN, accessToken, {
        httpOnly: false,
        secure: true,
        sameSite: "strict",
        maxAge: 2 * 1000,
      });
      res.cookie(MY_REFRESH_TOKEN, refreshToken, {
        httpOnly: false,
        secure: true,
        sameSite: "strict",
        maxAge: 1 * 1000 * 60 * 60 * 12,
      });
      return res.status(200).send({ ss });
    }
    return res.send("username or password is incorrect");
  });

  router.get("/refresh", (req, res) => {
    const refreshToken = req.cookies[MY_REFRESH_TOKEN];
    if (!refreshToken) {
      return res.status(403).send("Forbidden");
    }
    try {
      const { tel } = jwt.verify(refreshToken, SECRET);
      const accessToken = jwt.sign({ tel }, SECRET, { expiresIn: "10s" });
      res.cookie(MY_ACCESS_TOKEN, accessToken, {
        httpOnly: true,
        secure: true,
        sameSite: "strict",
        maxAge: 10 * 1000,
      });
      return res.status(200).send("Refreshed");
    } catch (error) {
      res.clearCookie(MY_REFRESH_TOKEN);
      return res.status(403).send("Forbidden");
    }
  });

  router.use((req, res, next) => {
    const accessToken = req.cookies[MY_ACCESS_TOKEN];
    if (!accessToken) {
      return res.status(401).send("Unauthorized");
    }
    try {
      const user = jwt.verify(accessToken, SECRET);
      res.locals.user = user;
      return next();
    } catch (error) {
      res.clearCookie(MY_ACCESS_TOKEN);
      return res.status(401).send("Unauthorized");
    }
  });

  router.get("/profile", (req, res) => {
    const { tel } = res.locals.user;
    return res.send(`Welcome ${tel}`);
  });

  

module.exports = router;
